package com.digitalchina.lxnsy.activity.old;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessTraining;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.base.BaseApplication;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.SelectedCityVO;
import com.digitalchina.lxnsy.entity.TrainVO;
import com.digitalchina.lxnsy.service.LocationService;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.TrainInfoListHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static com.digitalchina.lxnsy.activity.old.AddressSelectActivity.KEY_PICKED_CITY;
import static com.digitalchina.lxnsy.activity.old.SearchViewActivity.RESULT_CODE_TRAINING_SEARCH;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：新版培训签到列表
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/2/27 10:52
 * 修改备注：
 * ================================================
 */

public class TrainInfoListActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.sign_in_tv_location)
    TextView signInTvLocation;
    @Bind(R.id.sign_in_tv_search)
    TextView signInTvSearch;
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;

    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;
    private String keyWord = "";
    //    private String provinceCode = "";
//    private String cityCode = "";
//    private String countyCode = "";
    private String cityName = "";
    private int msgWhat;

    //LBS
    private final int SDK_PERMISSION_REQUEST = 127;
    private final int LBS_SUCCESS = 128;
    private final int LOCATION_REQUEST_CODE = 129;

    private String permissionInfo;
    private LocationService locationService;
    private boolean isLocationSuccess = false;
    private BDLocation mLocation; // 定位信息
    private boolean isFromLocation = true;
    private boolean isFromSearch = false;
    private boolean isFromSign = false;
    private SelectedCityVO cityVO = new SelectedCityVO();

    private List<TrainVO> trainVOList = new ArrayList<>();

    private final int SEARCH_REQUEST = 130;
    private final int SIGN_REQUEST = 131;
    private final int EVALUATE_REQUEST_CODE = 132;

    @Override
    public void setLayout() {
        setTitle("培训信息");
        setContentLayout(R.layout.activity_sign_in_list);
        getPersimmions();
    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }

        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == SDK_PERMISSION_REQUEST) {
            locationService.start();
        }

    }

    /***
     * Stop location service
     */
    @Override
    protected void onStop() {
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }


    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location) {

                if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    isLocationSuccess = true;
                    locationService.stop();
                } else {
                    isLocationSuccess = false;
                    locationService.stop();
                }

                Message message = new Message();
                message.what = LBS_SUCCESS;
                message.obj = location;
                mHandler.sendMessage(message);

            }

        }

        public void onConnectHotSpotMessage(String s, int i) {
        }
    };

    @Override
    public void initMember() {
        initRecyclerView();

        // -----------location config ------------
        locationService = ((BaseApplication) getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        int type = getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
        locationService.start();
    }

    private void initRecyclerView() {


        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, false, false));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new TrainInfoListHolder(parent);
            }
        });

    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                GotoUtil.gotoActivity(TrainInfoListActivity.this, AgriculturalTrainingDetailsActivity.class, "toTrainDetails", adapter.getAllData().get(position));
            }
        });

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                msgWhat = msg.what;

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_GET_TRAINING_IN_CITY_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_TRAINING_IN_CITY_FIELD:
                        showToast(msg.obj.toString());
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case LBS_SUCCESS:
                        callBack(msg.obj);
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

        switch (msgWhat) {
            case MSG.MSG_GET_TRAINING_IN_CITY_SUCCESS:

                trainVOList = FastJsonUtil.getListBean(object.toString(), "body", "agriTrainings", TrainVO.class);

                if (null == trainVOList || mLocation == null || mLocation.getAddress() == null)
                    return;

//                if (isFromLocation) {
                for (int i = 0; i < trainVOList.size(); i++) {
                    trainVOList.get(i).setLocationAddress(mLocation.getAddress().city);
                }
//                }
//                else {
//                    for (int i = 0; i < trainVOList.size(); i++) {
//                        trainVOList.get(i).setLocationAddress(cityVO.getCityName() != null ? cityVO.getCityName() : "");
//                    }
//                }

                if (page == 1) { // 刷新
                    adapter.clear();
                }

                if (trainVOList != null) {
                    if (trainVOList.size() < limit) {
                        adapter.stopMore();
                    }
                }

                adapter.addAll(trainVOList);

                break;
            case LBS_SUCCESS:

                mLocation = (BDLocation) object;
                if (isFromLocation) {
                    if (mLocation.getAddress().city != null && mLocation.getAddress().district != null) {
                        signInTvLocation.setText(StringUtil.jointString(mLocation.getAddress().city, mLocation.getAddress().district));
                        cityName = mLocation.getAddress().city;
                        onRefresh();
                    } else
                        signInTvLocation.setText("定位失败, 请选择地址");
                }

                break;
        }


    }


    @Override
    public void rightOnClick() {

    }

    @OnClick({R.id.sign_in_tv_location, R.id.sign_in_tv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sign_in_tv_location:
                if (null == cityVO.getCityName() && null != mLocation) {
                    cityVO.setCityName(mLocation.getAddress().city);
                    cityVO.setCountyName(mLocation.getAddress().district);
                }
                GotoUtil.gotoForResultActivity(TrainInfoListActivity.this, AddressSelectActivity.class, LOCATION_REQUEST_CODE, "selectCityVO", cityVO);
                break;
            case R.id.sign_in_tv_search:

                GotoUtil.gotoForResultActivity(this, SearchViewActivity.class, SEARCH_REQUEST);

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOCATION_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                isFromLocation = false;
                Bundle bundle = data.getExtras();
                cityVO = (SelectedCityVO) bundle.get(KEY_PICKED_CITY);
                if (cityVO == null)
                    return;

                if (null != cityVO.getCountyCode() && null != cityVO.getCityName()) { // 含有区 显示 市区
                    cityName = cityVO.getCityName();
                    signInTvLocation.setText(StringUtil.jointString(cityVO.getCityName(), cityVO.getCountyName()));
                    if (!cityName.equals(cityVO.getCityName())) // 切换了城市 刷新列表
                        onRefresh();
                } else if (!cityName.equals(cityVO.getCityName())) { // 只含有 市 显示 市
                    cityName = cityVO.getCityName();
                    signInTvLocation.setText(cityVO.getCityName());
                    onRefresh();
                } else { // 城市名相同 不做refresh
                    signInTvLocation.setText(cityVO.getCityName());
                }
            }
        } else if (requestCode == SEARCH_REQUEST) {
            isFromLocation = false;
            if (null != data && resultCode == RESULT_CODE_TRAINING_SEARCH) {
                //搜索返回数据
                if (null != keyWord || !"".equals(keyWord))
                    keyWord = "";
                if (null != adapter || adapter.getAllData().size() > 0) {
                    adapter.clear();
                    adapter.notifyDataSetChanged();
                }
                keyWord = data.getStringExtra("KeyWord");

                searchData();
            }
        } else if (requestCode == EVALUATE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                for (int i = 0; i < adapter.getAllData().size(); i++) {
                    if (((TrainVO) adapter.getAllData().get(i)).getId().equals(data.getStringExtra("trainingId"))) {
                        ((TrainVO) adapter.getAllData().get(i)).setIsEvaluate(true);
                        adapter.notifyDataSetChanged();
                    }
                }

            }
        }
    }

    /**
     * 根据关键字 搜索
     */
    private void searchData() {
        signInTvSearch.setText(keyWord);
        page = 1;
        BusinessTraining.getTrainingByKeywords(this, keyWord, String.valueOf(page), String.valueOf(limit), mHandler);
//        BusinessTraining.getTrainingList(this, String.valueOf(page), String.valueOf(limit),
//                "", "", "", keyWord,
//                provinceCode, cityCode, countyCode, mHandler);
    }

    @Override
    public void onRefresh() {
        page = 1;
        keyWord = "";
        signInTvSearch.setText(keyWord);
//        if (StringUtil.isStrEmpty(keyWord))
        BusinessTraining.getTrainingInCity(this, cityName, String.valueOf(page), String.valueOf(limit), mHandler);
//        else
//            BusinessTraining.getTrainingByKeywords(this, keyWord, String.valueOf(page), String.valueOf(limit), mHandler);
//        BusinessTraining.getTrainingList(this, String.valueOf(page), String.valueOf(limit),
//                "", "", "", keyWord,
//                provinceCode, cityCode, countyCode, mHandler);
    }

    @Override
    public void onLoadMore() {

            page++;
            if (StringUtil.isStrEmpty(keyWord))
                BusinessTraining.getTrainingInCity(this, cityName, String.valueOf(page), String.valueOf(limit), mHandler);
            else
                BusinessTraining.getTrainingByKeywords(this, keyWord, String.valueOf(page), String.valueOf(limit), mHandler);

    }

}
